package com.zxl.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestUrl {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String cmd = "";
		
		while(true){
			System.out.println("------------------------");
			System.out.println("  1.测试一个地址；");
			System.out.println("  2.测试配置文件里的所有地址；");
			System.out.println("  3.退出；");
			System.out.println("------------------------");
			System.out.println("请选择：");
			
			String command = inputCommand();
			Long st = System.currentTimeMillis();
			if(command != null && !command.equals("")){
				if(command.length() > 1){
					System.out.println("未识别，请重新输入！");
					continue;
				}
				
				int n = Integer.parseInt(command);
				switch(n){
				case 1:
					System.out.println("请输入要测试的地址：");
					cmd = inputCommand();
					testUrl(cmd);
					break;
				case 2:
					try{
						String path = "";
						String filename = "url.txt";
					    
					    path = getResourcePath();
					    ArrayList urllist = (ArrayList) ReadConfFile(path + filename);
					    
					    for(int i = 0; i < urllist.size(); i++){
					    	Map m = (Map) urllist.get(i);
					    	System.out.println(m.get("adnm").toString());
					    	testUrl(m.get("appurl").toString());
					    }
					}catch(Exception e){
						e.printStackTrace();
					}
					break;
				case 3:
					System.exit(0);
				default:
					System.out.println("未识别，请重新输入！");
				}
			}else{
				System.out.println("不能为空！");
			}
			
			Long et = System.currentTimeMillis();
			Long l = et-st;
			if(l < 1000){
				System.out.println("耗时" + l + "毫秒");
			}else if(l < 60000){
				System.out.println("耗时" + l/1000 + "秒");
			}else{
				System.out.println("耗时" + l/60000 + "分钟");
			}
		
		}

	}
	
	/**
	 * 输入命令
	 * @return
	 */
	public static String inputCommand(){
		String command = "";
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		try {
			command = bf.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return command;
	}
	
	/**
	 * 测试地址是否可访问
	 * @param appurl
	 */
	public static void testUrl(String appurl){
		
		try {
			if(!appurl.startsWith("http://")){
				appurl = "http://" + appurl;
			}
			System.out.println(appurl);
			URL url = new URL(appurl);
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			String str = conn.getHeaderField(0);
			if(str != null){
				if (str.indexOf("OK") > 0) {
					System.out.println("可以访问！");
				} else {
					System.out.println("不能访问！");
				}
			}else{
				System.out.println("不能访问！");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * 读取配置文件
	 * @param filepath
	 * @return
	 */
	public static List ReadConfFile(String filepath){
		List urllist = new ArrayList();
		File file = new File(filepath);
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                if(tempString.startsWith("#")){
                	continue;
                }else{
                	Map m = new HashMap();
                	String url[] = tempString.split("\t");
                	if(url.length > 1){
	                	m.put("adnm", url[0]);
	                	m.put("appurl", url[1]);
	                	urllist.add(m);
                	}
                }
            }
            reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
            	try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        }
        return urllist;
	}
	
	/**
	 * 获取类的当前目录
	 * @return
	 */
	private static String getResourcePath() {
		String className = TestUrl.class.getName();
		String classNamePath = className.replace(".", "/") + ".class";
		URL is = TestUrl.class.getClassLoader().getResource(classNamePath);
		String path = is.getFile();
		int n = path.lastIndexOf("/");
		path = path.substring(0, n+1);
		
		//如果访问的是jar包里的路径，则返回jar包的当前目录
		int m = path.indexOf("!");
		if(m != -1){
			path = path.substring(0, m);
			m = path.indexOf("/");
			n = path.lastIndexOf("/");
			path = path.substring(m, n+1);
		}

		return path;
	}

}
